//
//  ST_CloseFriendsViewController.swift
//  btvideo
//
//  Created by Jason on 2021/9/6.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import RxDataSources
import MJRefresh
import SwiftyUserDefaults

class ST_CloseFriendsViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.currentPage = 0
            self?.request_data()
        })
        
        binding()
        
    }
    
    fileprivate func binding(){
        
        let datasource = RxCollectionViewSectionedReloadDataSource<SectionModel<String,ST_GiftRankCellModel>>.init { dataSource, collectionView, indexPath, model in
            
            switch indexPath.row{
                
            case 0...2:
                
                let cell = collectionView.dequeueReusableCell(withClass: CloseFriendsCrownCell.self, for: indexPath)
                
                cell.model = model
                
                return cell
                
            default:
                let cell = collectionView.dequeueReusableCell(withClass: CloseFriendsNormalCell.self, for: indexPath)
                
                cell.model = model
                
                return cell
            }
            
            
        }
        
        data_list_observable.map({ [SectionModel<String,ST_GiftRankCellModel>(model: "", items: $0)] }).bind(to: self.collectionView.rx.items(dataSource: datasource)).disposed(by: self.disposeBag)
        
        
        collectionView.rx.itemSelected.subscribe(onNext: {[weak self] indexPath in
            
            guard let model = self?.data_list_observable.value[safe: indexPath.row] else{
                return
            }
            
            let vc = ST_PairsCenterViewController()
            
            vc.accid = model.accid
            
            let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
            
            nav.overCurrentContext = true
            
            GlobalPresent(toController: nav)
            
        }).disposed(by: disposeBag)
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f == true{
                own.currentPage = 0
                own.request_data()
            }else{
                own.data_list_observable.accept([])
            }
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    fileprivate var currentPage = 0
    
    fileprivate func request_data(){
        
        
        currentPage += 1
        
        
        JVrequest(PH.getGoodsRankApi,parameters: ["page":self.currentPage,"size":20], success: { (json) in
            
            let list =  json["data"].arrayValue.enumerated().map { (index, element) in
                ST_GiftRankCellModel.init(fromJson: element, row: index)
            }
            
            let responseCount = list.count
            
            if self.currentPage == 1{
                
                self.data_list_observable.accept(list)
                
            }else{
                
                self.data_list_observable.accept(self.data_list_observable.value + list)
            }
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
            self.load_more_option_style(tableView: self.collectionView, count: responseCount, pageSize: 20) {
                
                self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    self?.request_data()
                })
            }
            
        }) { (code, err) in
            
            
            self.toast(text: err)
        }
        
        
    }
    //    MARK: - Properties
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.scrollDirection = .vertical
        controlLayout.minimumLineSpacing = 15
        controlLayout.minimumInteritemSpacing = 15
        
        controlLayout.sectionInset = UIEdgeInsets.init(top: 15, left: 0, bottom: 0, right: 0)
        let w = ScreenWidth - 30
        controlLayout.itemSize = CGSize.init(width: w, height: 80)
        
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        
        control.register(cellWithClass: CloseFriendsNormalCell.self)
        control.register(cellWithClass: CloseFriendsCrownCell.self)
        
        control.emptyDataSetSource = self
        control.emptyDataSetDelegate = self
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: BTSafeAreaBottom + 55, right: 0)
        control.backgroundColor = UIColor.white
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    var disposeBag = DisposeBag()
    
    fileprivate var first = true
    
    fileprivate let data_list_observable = BehaviorRelay(value: [ST_GiftRankCellModel]())
}





extension ST_CloseFriendsViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
        return true
    }
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
        
        if first{
            self.first = false
            return false
        }else{
            return true
        }
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        
        let attrString = NSMutableAttributedString(string: "暂时还没有密友哦\n晚点再来看看")
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        
        return ST_ImageUtils.imageName("首页_img_活跃(空)")
    }
}
